package com.heima.wemedia.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult login(WmLoginDto dto) {
        List<WmUser> wmUsers = wmUserMapper.selectList (Wrappers.<WmUser>lambdaQuery ()
                .eq (WmUser::getName, dto.getName ()));
        if (ObjectUtil.isEmpty (wmUsers)) {
            return ResponseResult.errorResult (AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        for (WmUser wmUser: wmUsers) {
//            System.out.println (apUser.getPassword ());
//            System.out.println (dto.getPassword ());
            //数据库
            if(BCrypt.checkpw (dto.getPassword (), wmUser.getPassword ())){
                Map<String, Object> data = new HashMap<> ();
                Map<String, Object> user = new HashMap<> ();
                user.put ("id", wmUser.getId ());
                user.put ("apUserId", wmUser.getApUserId ());
                user.put ("apAuthorId", wmUser.getApAuthorId ());
                user.put ("name", wmUser.getName ());
                user.put ("password", "");
                user.put ("nickname", wmUser.getNickname ());
                user.put ("image", wmUser.getImage ());
                user.put ("location", wmUser.getLocation ());
                user.put ("status", wmUser.getStatus ());
                user.put ("phone", wmUser.getPhone ());
                user.put ("email", wmUser.getEmail ());
                user.put ("type", wmUser.getType ());
                user.put ("score", wmUser.getScore ());
                user.put ("loginTime", wmUser.getLoginTime ());
                user.put ("createdTime", wmUser.getCreatedTime ());
                data.put ("user", user);
                String token = AppJwtUtil.getToken (Long.valueOf (wmUser.getId ()));
                data.put ("token", token);
                return ResponseResult.okResult (data);
            }
        }

        return ResponseResult.errorResult (AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
       //TODO
    }
}